package com.github.postsanf.yinian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.ActivityActivity;
import com.github.postsanf.yinian.activity.AwardActivity;
import com.github.postsanf.yinian.activity.LinkActivity;
import com.github.postsanf.yinian.activity.MyWalletDialogActivity;
import com.github.postsanf.yinian.activity.NewsActivity;
import com.github.postsanf.yinian.activity.ProfileActivity;
import com.github.postsanf.yinian.activity.SettingActivity;
import com.github.postsanf.yinian.activity.TimeGoodsShopActivity;
import com.github.postsanf.yinian.activity.TodayShowActivity;
import com.github.postsanf.yinian.activity.pop.MinePopMenu;
import com.github.postsanf.yinian.activity.pop.PopMenuItem;
import com.github.postsanf.yinian.adapter.TimeLineMineNewStatusAdapter;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.bean.YNUserStoragePlace;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNLoginResponse;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.service.UserStatusService;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class MineFragement extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private TextView toolbar_white;
    private RecyclerView rv_user_status_list;
    private SimpleDraweeView mUserStatusBG;
    private ImageView mine_empty_status;
    private SimpleDraweeView iv_user_status_avatar;
    private TextView tv_user_status_nickname;
    private ProgressBar mine_progressbar;
    private TextView mine_rongliang;
    private ImageView iv_news_point;
    private TimeLineMineNewStatusAdapter mAdapter;
    private ImageView right_more;
    private boolean isBottom;
    private boolean aIsChat;
    private String noteName;
    public static String avatarPic = "";
    public static String nickname = "";
    private boolean refresh = false;
    private MinePopMenu mPopMenu;
    private List<YNStatus> groupStatusItems = new ArrayList<>();
    private int overallXScroll = 0;
    private LinearLayoutManager manager;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        registerBoradcastReceiver();
    }


    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.yn_activity_mine_new, null);
        toolbar_white = (TextView) view.findViewById(R.id.toolbar_white);
        right_more = (ImageView) view.findViewById(R.id.right_more);
        right_more.setOnClickListener(this);
        rv_user_status_list = (RecyclerView) view.findViewById(R.id.rv_user_status_list);
        iv_news_point = (ImageView) view.findViewById(R.id.iv_news_point);
        view.findViewById(R.id.right_bell).setOnClickListener(this);
        manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(OrientationHelper.VERTICAL);
        rv_user_status_list.setLayoutManager(manager);
        View headview = LayoutInflater.from(getActivity()).inflate(
                R.layout.yn_activity_minenew_top, null, false);
        mAdapter = new TimeLineMineNewStatusAdapter(getActivity(), groupStatusItems, application.getCurID(), false, headview);
        rv_user_status_list.setAdapter(mAdapter);
        mine_empty_status = (ImageView) headview.findViewById(R.id.mine_empty_status);
        mUserStatusBG = (SimpleDraweeView) headview.findViewById(R.id.iv_user_status_album_top);
        iv_user_status_avatar = (SimpleDraweeView) headview.findViewById(R.id.iv_user_status_avatar);
        iv_user_status_avatar.setOnClickListener(this);
        tv_user_status_nickname = (TextView) headview.findViewById(R.id.tv_user_status_nickname);
        mine_progressbar = (ProgressBar) headview.findViewById(R.id.mine_progressbar);
        mine_rongliang = (TextView) headview.findViewById(R.id.mine_rongliang);
        headview.findViewById(R.id.mine_dayin).setOnClickListener(this);
        headview.findViewById(R.id.mine_tongbu).setOnClickListener(this);
        headview.findViewById(R.id.mine_jiaocheng).setOnClickListener(this);
        headview.findViewById(R.id.mine_kongjianjiangli).setOnClickListener(this);
        headview.findViewById(R.id.mine_mywallet).setOnClickListener(this);
        rv_user_status_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                if ((visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && (((LinearLayoutManager) layoutManager).findLastVisibleItemPosition()) >= totalItemCount - 1)) {
                    if (isBottom) {
                        return;
                    }
                    LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_user_status_list);
                    if (state == LoadingFooter.State.Loading) {
                        return;
                    }
//                    RecyclerViewStateUtils.setFooterViewState(getActivity(), rv_user_status_list, 10, LoadingFooter.State.Loading, null);
                    rv_user_status_list.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadStatus(false);
                        }
                    }, 500);
                }
            }
        });
        rv_user_status_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(-1)) {
                    toolbar_white.setAlpha(0);
                    overallXScroll = 0;
                }
                overallXScroll = overallXScroll + dy;
                if (overallXScroll < 121) {
                    float ii = (float) overallXScroll / 120;
                    toolbar_white.setAlpha(ii);
                } else {
                    toolbar_white.setAlpha(1);
                }
            }
        });
        initPop();
        initGetSpace();
        noticeServiceInit(application.getCurID(), 0);
        Intent mIntent = new Intent(getActivity(), UserStatusService.class);
        mIntent.setAction(ACTIONs.actionGetTop);
        mIntent.putExtra(ACTIONs.aUserId, application.getCurID());
        getActivity().startService(mIntent);
        return view;
    }

    private void initGetSpace() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUserData))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "GB===>" + s);
                        YNUserStoragePlace userStoragePlace = gson.fromJson(s, YNUserStoragePlace.class);
                        if (userStoragePlace.getData().size() != 0) {
                            double totalSpaceToGB = getSpaceToGB(userStoragePlace.getData().get(0).getUtotalspace());
                            double useSpaceToGB = getSpaceToGB(userStoragePlace.getData().get(0).getUusespace());
                            String format = new DecimalFormat("#").format((useSpaceToGB / totalSpaceToGB) * 100);
                            mine_progressbar.setProgress(Integer.parseInt(format));
                            String showUse = getSpaceToGBOrMB(userStoragePlace.getData().get(0).getUusespace());
                            String showTotal = new DecimalFormat("####.00").format(totalSpaceToGB);
                            mine_rongliang.setText("已用容量" + showUse + "/总容量" + showTotal + "G");
                        }
                        super.onSuccess(s, response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private double getSpaceToGB(double totalSpace) {
        double totalSpcaeGB = totalSpace / 1024 / 1024;
        return totalSpcaeGB;
    }

    private String getSpaceToGBOrMB(double totalSpace) {
        if (totalSpace > 1024 * 1024) {
            DecimalFormat useFormat = new DecimalFormat("###0.00");//四舍五入不保留小数
            return useFormat.format(totalSpace / 1024 / 1024) + "G";
        } else {
            DecimalFormat useFormat = new DecimalFormat("#");//四舍五入不保留小数
            return useFormat.format(totalSpace / 1024) + "M";
        }
    }

    private void initPop() {
        mPopMenu = new MinePopMenu(getActivity(), UIHelper.dip2px(getActivity(), 125),
                UIHelper.dip2px(getActivity(), 85));
        mPopMenu.setItemOnClickListener(onitemClick);
        mPopMenu.addAction(new PopMenuItem(getActivity(), "设置"));
        mPopMenu.addAction(new PopMenuItem(getActivity(), "今日忆"));
//        mPopMenu.addAction(new PopMenuItem(getActivity(), "私人相册"));
    }

    private MinePopMenu.OnItemOnClickListener onitemClick = new MinePopMenu.OnItemOnClickListener() {
        @Override
        public void onItemClick(PopMenuItem item, int position) {
            switch (position) {
                case 0:
                    intent2Activity(SettingActivity.class);
                    break;
                case 1:
                    intent2Activity(TodayShowActivity.class);
                    getActivity().overridePendingTransition(R.anim.slide_up_in, R.anim.none_out);
                    break;
//                case 2:
//                    intent2Activity(GuideImportActivity.class);
//                    break;
            }
        }
    };


    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                mRefreshlayout.setRefreshing(false);
            }
        }, 500);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_user_status_avatar:
                intent2Activity(ProfileActivity.class);
                break;
            case R.id.right_bell:
                intent2Activity(NewsActivity.class);
                break;
            case R.id.mine_dayin:
                intent2Activity(TimeGoodsShopActivity.class);
                break;
            case R.id.mine_tongbu:
                intent2Activity(LinkActivity.class);
                break;
            case R.id.mine_jiaocheng:
                intent2Activity(ActivityActivity.class);
                break;
            case R.id.mine_kongjianjiangli:
                intent2Activity(AwardActivity.class);
                break;
            case R.id.mine_mywallet:
                startActivity(new Intent(getActivity(), MyWalletDialogActivity.class));
                break;
            case R.id.right_more:
                mPopMenu.show(right_more);
                break;
        }
    }


    private void updateView2(List<YNStatus> statusLists) {
//        mRefreshlayout.setRefreshing(false);
        mAdapter.addItemsFromBottom(statusLists);
        if (statusLists.size() == 0) {
            isBottom = true;
            RecyclerViewStateUtils.setFooterViewState(getActivity(), rv_user_status_list, 10, LoadingFooter.State.TheEnd, null);
        } else {
            RecyclerViewStateUtils.setFooterViewState(rv_user_status_list, LoadingFooter.State.Normal);
        }
    }


    private void loadStatus(boolean isTop) {
        noticeServiceInit(application.getCurID(), mAdapter.getIdByDirection(isTop));
    }

    BroadcastReceiver mUserStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionUserTop:
                    YNUser user = (YNUser) intent.getSerializableExtra(ACTIONs.aAddData);
                    avatarPic = user.getUpic();
                    ImageOptHelper.showFrescoAvatar(Uri.parse(YNUrlHelper.getStatusUrl(getActivity(), user.getUbackground())), mUserStatusBG, getActivity());
                    nickname = user.getUnickname();
                    if (!StringUtils.isEmpty(avatarPic)) {
                        ImageOptHelper.showFrescoAvatar(Uri.parse(YNUrlHelper.getAvatarUrl(getActivity(), avatarPic)), iv_user_status_avatar, getActivity());
                    }
                    if (aIsChat) {
                        if (!StringUtils.isEmpty(noteName)) {
                            tv_user_status_nickname.setText(noteName);
                        } else {
                            tv_user_status_nickname.setText(user.getUnickname());
                        }
                    } else {
                        tv_user_status_nickname.setText(user.getUnickname());
                    }
                    break;
                case ACTIONs.actionStatus:
                    boolean isAdd = intent.getExtras().getBoolean(ACTIONs.IsAdd);
                    int statusID = intent.getExtras().getInt(ACTIONs.StatusId);
                    doSyncStatus(isAdd, statusID);
                    break;
                case ACTIONs.actionComment:
                    mAdapter.SyncComment();
                    break;
                case ACTIONs.actionSinglePhoto:
                    mAdapter.SyncDelSingle();
                    break;
                case ACTIONs.modifyStatus:
                    refresh = true;
                    noticeServiceInit(application.getCurID(), 0);
                    break;
                case ACTIONs.Avatar:
                    String avatarUri = intent.getStringExtra("avatarUri");
                    ImageOptHelper.showFrescoNative(Uri.parse("file://" + avatarUri), iv_user_status_avatar, getContext());
                    break;
                case ACTIONs.actionAlertMeBg:
                    getUserTop(application.getCurID());
                    refresh = true;
                    noticeServiceInit(application.getCurID(), 0);
                    break;
                case ACTIONs.actionMymessageNums:
                    SharedPreferences preferences = context.getSharedPreferences(
                            ACTIONs.mymsg, 0);
                    boolean invitebb = preferences.getBoolean(ACTIONs.invitebb, false);
                    boolean commentbb = preferences.getBoolean(ACTIONs.commentbb, false);
                    boolean notifybb = preferences.getBoolean(ACTIONs.notifybb, false);
                    int invitenum = preferences.getInt(ACTIONs.invitenum, 0);
                    int commentnum = preferences.getInt(ACTIONs.commentnum, 0);
                    int notifynum = preferences.getInt(ACTIONs.notifynum, 0);
                    int totalnum = invitenum + commentnum + notifynum;
                    if (invitebb || commentbb || notifybb) {
                        iv_news_point.setVisibility(View.VISIBLE);
                    } else {
                        iv_news_point.setVisibility(View.GONE);
                    }
                    break;
                case ACTIONs.actionLike:
                    mAdapter.SyncLike();
                    break;
                case "EMPTY_VIEW":
                    if (intent.getBooleanExtra("show", false)) {
                        mine_empty_status.setVisibility(View.VISIBLE);
                    } else {
                        mine_empty_status.setVisibility(View.GONE);
                    }
                    break;
                case "TopTitleGone":
                    overallXScroll = 0;
                    toolbar_white.setAlpha(0);
                    break;
                case "updateRongLiangShow":
                    initGetSpace();
                    break;
            }
        }
    };

//    private void initIsAward() {
//        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
//        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
//        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/yinian/UserStoragePlaceCondition")
//                .setMethod(HttpMethods.Post)
//                .setParamMap(mParam)
//                .setHttpListener(new HttpListener<String>() {
//                    @Override
//                    public void onSuccess(String s, Response<String> response) {
//                        YNUserStorageAward storageAward = gson.fromJson(s, YNUserStorageAward.class);
//                        if (storageAward.getData().size() != 0) {
//                            int uInviteReward = storageAward.getData().get(0).getUInviteReward();
//                            int uCreateReward = storageAward.getData().get(0).getUCreateReward();
//                            int uJoinReward = storageAward.getData().get(0).getUJoinReward();
//                            if (uInviteReward == 2 || uCreateReward == 2 || uJoinReward == 2) {
//                                iv_space.setVisibility(View.VISIBLE);
//                            } else {
//                                iv_space.setVisibility(View.GONE);
//                            }
//                        }
//                        super.onSuccess(s, response);
//                    }
//
//                    @Override
//                    public void onFailure(HttpException e, Response<String> response) {
////                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
//                    }
//                });
//        liteHttp.executeAsync(req);
//    }

    // 获取成员头信息
    private void getUserTop(int userid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNLoginResponse resUser = gson.fromJson(s, YNLoginResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            YNUser user = resUser.getData().get(0);
                            Uri bgUri = Uri.parse(YNUrlHelper.getStatusUrl(getContext(), user.getUbackground()));
                            ImageOptHelper.showFrescoAvatar(bgUri, mUserStatusBG, getContext());
                            avatarPic = user.getUpic();
                            nickname = user.getUnickname();
                            ImageOptHelper.showFrescoAvatar(Uri.parse(YNUrlHelper.getAvatarUrl(getContext(), avatarPic)), iv_user_status_avatar, getContext());
                            tv_user_status_nickname.setText(user.getUnickname());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 同步动态
    private void doSyncStatus(boolean isAdd, int statusID) {
        if (isAdd) {
            if (statusID == YNSingleton.getInstance().getCurStatus().getEid()) {
                mAdapter.addItemsFromTopOne(YNSingleton.getInstance().getCurStatus());
                rv_user_status_list.scrollToPosition(0);
            }
        } else {
            mAdapter.removeOne(statusID);
        }
    }

    // 注册接收者
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionUserTop);
        myIntentFilter.addAction(ACTIONs.actionStatus);
        myIntentFilter.addAction(ACTIONs.actionComment);
        myIntentFilter.addAction(ACTIONs.actionSinglePhoto);
        myIntentFilter.addAction(ACTIONs.modifyStatus);
        myIntentFilter.addAction(ACTIONs.Avatar);
        myIntentFilter.addAction(ACTIONs.actionAlertMeBg);
        myIntentFilter.addAction(ACTIONs.actionMymessageNums);
        myIntentFilter.addAction(ACTIONs.actionDeleteList);
        myIntentFilter.addAction(ACTIONs.network);
        myIntentFilter.addAction(ACTIONs.actionLike);
        myIntentFilter.addAction("EMPTY_VIEW");
        myIntentFilter.addAction("TopTitleGone");
        myIntentFilter.addAction("updateRongLiangShow");
        getActivity().registerReceiver(mUserStatusBroadcastReceiver, myIntentFilter);
    }

    // 通知后台加载数据
    private void noticeServiceInit(int userid, int aLoadId) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        mParam.put(CommonConstants.YNS_MIN_ID, String.valueOf(aLoadId));
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/event/ShowMe2ndVersion")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resUserStatus = gson.fromJson(s, YNStatusResponse.class);
                        if (resUserStatus != null && ReqUtils.isSuccess(resUserStatus.getCode())) {
                            List<YNStatus> statusLists = new ArrayList<>();
                            statusLists.addAll(resUserStatus.getData());
                            if (refresh) {
                                mAdapter.update(statusLists);
                                mAdapter.notifyDataSetChanged();
                                refresh = false;
                            } else {
                                updateView2(statusLists);
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mUserStatusBroadcastReceiver);
    }


//    @Override
//    public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
//        Log.i("xjs", "iii===>" + i);
//        if (i > -121) {
//            float ii = (float) -i / 120;
//            toolbar_white.setAlpha(ii);
//        } else {
//            toolbar_white.setAlpha(1);
//        }
////        if (i == 0) {
////            mRefreshlayout.setEnabled(true);
////        } else {
////            mRefreshlayout.setEnabled(false);
////        }
//    }
//
//    public void onResume() {
//        super.onResume();
//        mAppBar.addOnOffsetChangedListener(this);
//    }
//
//    public void onPause() {
//        super.onPause();
//        mAppBar.removeOnOffsetChangedListener(this);
//    }

}
